#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <sms_core.h>


int main() {

    cv::Mat img;  // = cv::imread("/home/jario/Pictures/dji_stat_2024-12-30/DJI_20241013165423_0001_V_20241222_000001.jpg");  // cv::Mat::ones(480, 640, CV_8UC3) * 127;
    
    cv::VideoCapture cap("/home/jario/2024-11-12 13-12-58.mkv");

    const char* name = "/_My_Shm";  // 共享内存对象名称
    const int size = 1024*1024*60 ;         // 共享内存大小

    // 创建共享内存对象
    int shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        std::cerr << "Failed to create shared memory object" << std::endl;
        return 1;
    }

    // 设置共享内存大小
    if (ftruncate(shm_fd, size) == -1) {
        std::cerr << "Failed to set shared memory size" << std::endl;
        return 1;
    }

    // 映射共享内存到进程地址空间
    char* ptr = (char*)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED) {
        std::cerr << "Failed to map shared memory" << std::endl;
        return 1;
    }
    
    char* mpt;
    char* mend = ptr + size;
    mpt = ptr;

    while (1)
    {
    cap >> img;
    if (img.empty())
    {
    cap.set(cv::CAP_PROP_POS_FRAMES, 0);
    continue;
    }
    cv::resize(img, img, cv::Size(3840, 2160));
    // 写入数据到共享内存
    size_t img_siz = img.total() * img.elemSize();
    if (mpt + img_siz > mend)
    {
      mpt = ptr;
    }
    std::memcpy(mpt, img.data, img_siz);
    mpt += img_siz;
    sms::msleep(20);
    }
    // std::strcpy(ptr, "Hello from Process 1!");

    // 等待用户输入，以便进程 2 有时间读取数据
    std::cout << "Data written to shared memory. Press Enter to exit..." << std::endl;
    std::cin.get();

    // 解除映射
    munmap(ptr, size);

    // 关闭共享内存对象
    close(shm_fd);

    // 删除共享内存对象
    shm_unlink(name);

    return 0;
}

